package com.quectel.util.http;


import com.fasterxml.jackson.core.type.TypeReference;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.ex.http.HttpRequestSendException;
import lombok.Getter;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 两种使用方法
 * 1 建议使用多例 然后注入的形式
 *
 * @Bean
 * @Scope("prototype") public HttpRestUtils httpRestUtils(){
 * return HttpRestUtils.getDefaultInstance();
 * }
 * @Autowired private HttpRestUtils httpRestUtils;
 * 2 如果没有spring则直接在成员变量上
 * private static final HttpRestUtils HTTP_REST_UTILS=HttpRestUtils.getDefaultInstance();
 * <p>
 * <p>
 * 这里需要注意的地方：不要在每个方法实例化一封这样会造成资源浪费
 */
public class HttpRestUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpRestUtils.class);

    private static final String CHARSET = "UTF-8";

    @Getter
    private final HttpClient httpClient;


    private HttpRestUtils() {
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setSocketTimeout(5000)
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .build();
        httpClient = HttpClients.custom()
                .setDefaultRequestConfig(defaultRequestConfig)
                .setMaxConnTotal(500)
                .setMaxConnPerRoute(100)
                .setConnectionManagerShared(true)
                //重试1次
                .setRetryHandler(new DefaultHttpRequestRetryHandler(5, false))
                .build();
        LOGGER.info("Rest httpClient initialization completed");
    }


    private HttpRestUtils(HttpClient httpClient) {
        this.httpClient = httpClient;
        LOGGER.info("Rest httpClient initialization completed");
    }

    /**
     * 得到默认实例
     *
     * @return
     */
    public static HttpRestUtils getDefaultInstance() {
        return new HttpRestUtils();
    }

    /**
     * 得到绕过验证的ssl实例
     *
     * @return
     */
    public static HttpRestUtils getTrustSSLInstance() {
        SSLContext sslContext = null;
        try {
            sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {

                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }

            }).build();
        } catch (Exception e) {
            LOGGER.error("ssl初始化错误", e);
        }

        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setSocketTimeout(5000)
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .build();
        HttpClient sslHttpClient = HttpClients.custom()
                .setDefaultRequestConfig(defaultRequestConfig)
                .setSSLContext(sslContext)
                .setSSLHostnameVerifier(new NoopHostnameVerifier())
                .setMaxConnTotal(500)
                .setMaxConnPerRoute(100)
                //重试1次
                .setRetryHandler(new DefaultHttpRequestRetryHandler(5, false))
                .build();
        return getInstance(sslHttpClient);
    }

    /**
     * 得到自定义实例
     *
     * @param httpClient
     * @return
     */
    public static HttpRestUtils getInstance(HttpClient httpClient) {
        return new HttpRestUtils(httpClient);
    }

    private static final HttpRestUtils HTTP_REST_UTILS = HttpRestUtils.getDefaultInstance();

    public static void main(String[] args) {
        long l = System.currentTimeMillis();
        Pair<Integer, String> integerPair = HTTP_REST_UTILS.get("https://dev-smartcity.quectel.com:10443/smartvillage/cmsapi/home/operating/platformMessageNoticeList",
                null, null, new TypeReference<String>() {
                });

        System.out.println(integerPair.getValue());

        System.out.println("..." + (System.currentTimeMillis() - l));

    }

    /**
     * @param url
     * @param params
     * @param headers
     * @param typeReference new TypeReference<Response<HashMap<Integer,String>>>() {};
     * @param <T>
     * @return
     */
    public <T> Pair<Integer, T> get(String url,
                                    List<NameValuePair> params,
                                    Map<String, String> headers,
                                    TypeReference<T> typeReference
    ) {
        HttpResponse response = null;
        try {
            if (params != null && params.size() > 0) {
                StringBuilder sb = new StringBuilder();
                for (NameValuePair entry : params) {
                    sb.append("&").append(entry.getName()).append("=").append(entry.getValue());
                }
                if (url.contains("?")) {
                    url = url + sb.toString();
                } else {
                    url = url + "?" + sb.toString();
                }
            }
            HttpGet httpGet = new HttpGet(url.replace(" ", "%20"));
            headers = headers == null ? new HashMap<String, String>() : headers;

            headers.put("Content-Type", "application/json; charset=utf-8");
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpGet.setHeader(entry.getKey(), entry.getValue());
            }

            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, CHARSET);

            T t = null;
            if (typeReference.getType() == null || typeReference.getType() == String.class
                    || typeReference.getType() == Object.class
                    || typeReference.getType() == void.class || typeReference.getType() == Void.class) {
                t = (T) result;
            } else {
                t = JacksonUtils.parse(result, typeReference);
            }
            return Pair.of(response.getStatusLine().getStatusCode(), t);
        } catch (Exception e) {
            throw new HttpRequestSendException(e);
        } finally {
            if (response instanceof Closeable) {
                try {
                    ((Closeable) response).close();
                } catch (IOException e) {
                }
            }
        }
    }

    public <T> Pair<Integer, T> post(String url,
                                     Object params,
                                     Map<String, String> headers,
                                     TypeReference<T> typeReference) {
        HttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            if (params != null) {
                httpPost.setEntity(new StringEntity(params instanceof String ? params.toString() : JacksonUtils.toJsonString(params), CHARSET));
            }
            headers = headers == null ? new HashMap<String, String>() : headers;

            headers.put("Content-Type", "application/json");
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, CHARSET);

            T t = null;
            if (typeReference.getType() == null || typeReference.getType() == String.class
                    || typeReference.getType() == Object.class
                    || typeReference.getType() == void.class || typeReference.getType() == Void.class) {
                t = (T) result;
            } else {
                t = JacksonUtils.parse(result, typeReference);
            }
            return Pair.of(response.getStatusLine().getStatusCode(), t);
        } catch (Exception e) {
            throw new HttpRequestSendException(e);
        } finally {
            if (response instanceof Closeable) {
                try {
                    ((Closeable) response).close();
                } catch (IOException e) {
                }
            }
        }
    }

    /**
     * 这个流一定记得关闭 否则内存泄露
     * if (httpResponse instanceof Closeable) {
     * try {
     * ((Closeable)httpResponse).close();
     * } catch (IOException e) {
     * e.printStackTrace();
     * }
     * }
     *
     * @param url
     * @param params
     * @param headers
     * @return
     */
    public CloseableHttpResponse postBackHttpResponse(String url,
                                                      Object params,
                                                      Map<String, String> headers) {
        try {
            HttpPost httpPost = new HttpPost(url);
            if (params != null) {
                httpPost.setEntity(new StringEntity(params instanceof String ? params.toString() : JacksonUtils.toJsonString(params), CHARSET));
            }
            headers = headers == null ? new HashMap<String, String>() : headers;

            headers.put("Content-Type", "application/json");
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
            return (CloseableHttpResponse) httpClient.execute(httpPost);
        } catch (Exception e) {
            throw new HttpRequestSendException(e);
        }
    }

    public <T> Pair<Integer, T> postForm(String url,
                                         List<NameValuePair> params,
                                         Map<String, String> headers,
                                         TypeReference<T> typeReference) {
        HttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            if (params != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            }
            headers = headers == null ? new HashMap<String, String>() : headers;

            headers.put("Content-Type", "application/x-www-form-urlencoded");
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, CHARSET);

            T t = null;
            if (typeReference.getType() == null || typeReference.getType() == String.class
                    || typeReference.getType() == Object.class
                    || typeReference.getType() == void.class || typeReference.getType() == Void.class) {
                t = (T) result;
            } else {
                t = JacksonUtils.parse(result, typeReference);
            }
            return Pair.of(response.getStatusLine().getStatusCode(), t);
        } catch (Exception e) {
            throw new HttpRequestSendException(e);
        } finally {
            if (response instanceof Closeable) {
                try {
                    ((Closeable) response).close();
                } catch (IOException e) {
                }
            }
        }
    }

    public <T> Pair<Integer, T> upFile(String url,
                                       Pair<String, File> filePair,
                                       Map<String, String> headers,
                                       TypeReference<T> typeReference) {
        HttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.addBinaryBody(filePair.getLeft(), filePair.getRight());
            HttpEntity httpEntity = multipartEntityBuilder.build();
            httpPost.setEntity(httpEntity);
            headers = headers == null ? new HashMap<String, String>() : headers;

            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, CHARSET);

            T t = null;
            if (typeReference.getType() == null || typeReference.getType() == String.class
                    || typeReference.getType() == Object.class
                    || typeReference.getType() == void.class || typeReference.getType() == Void.class) {
                t = (T) result;
            } else {
                t = JacksonUtils.parse(result, typeReference);
            }
            return Pair.of(response.getStatusLine().getStatusCode(), t);
        } catch (Exception e) {
            throw new HttpRequestSendException(e);
        } finally {
            if (response instanceof Closeable) {
                try {
                    ((Closeable) response).close();
                } catch (IOException e) {
                }
            }
        }
    }

    public <T> Pair<Integer, T> put(String url,
                                    Object params,
                                    Map<String, String> headers,
                                    TypeReference<T> typeReference) {
        HttpResponse response = null;
        try {
            HttpPut httpPut = new HttpPut(url);
            if (params != null) {
                httpPut.setEntity(new StringEntity(params instanceof String ? params.toString() : JacksonUtils.toJsonString(params), CHARSET));
            }
            headers = headers == null ? new HashMap<String, String>() : headers;

            headers.put("Content-Type", "application/json");
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPut.setHeader(entry.getKey(), entry.getValue());
            }
            response = httpClient.execute(httpPut);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, CHARSET);

            T t = null;
            if (typeReference.getType() == null || typeReference.getType() == String.class
                    || typeReference.getType() == Object.class
                    || typeReference.getType() == void.class || typeReference.getType() == Void.class) {
                t = (T) result;
            } else {
                t = JacksonUtils.parse(result, typeReference);
            }
            return Pair.of(response.getStatusLine().getStatusCode(), t);
        } catch (Exception e) {
            throw new HttpRequestSendException(e);
        } finally {
            if (response instanceof Closeable) {
                try {
                    ((Closeable) response).close();
                } catch (IOException e) {
                }
            }
        }
    }

    public <T> Pair<Integer, T> delete(String url,
                                       Object params,
                                       Map<String, String> headers,
                                       TypeReference<T> typeReference) {
        HttpResponse response = null;
        try {
            HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
            if (params != null) {
                httpDelete.setEntity(new StringEntity(params instanceof String ? params.toString() : JacksonUtils.toJsonString(params), CHARSET));
            }
            headers = headers == null ? new HashMap<String, String>() : headers;

            headers.put("Content-Type", "application/json");
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpDelete.setHeader(entry.getKey(), entry.getValue());
            }
            response = httpClient.execute(httpDelete);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, CHARSET);
            T t = null;
            if (typeReference.getType() == null || typeReference.getType() == String.class
                    || typeReference.getType() == Object.class
                    || typeReference.getType() == void.class || typeReference.getType() == Void.class) {
                t = (T) result;
            } else {
                t = JacksonUtils.parse(result, typeReference);
            }
            return Pair.of(response.getStatusLine().getStatusCode(), t);
        } catch (Exception e) {
            throw new HttpRequestSendException(e);
        } finally {
            if (response instanceof Closeable) {
                try {
                    ((Closeable) response).close();
                } catch (IOException e) {
                }
            }
        }
    }

    static class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
        public static final String METHOD_NAME = "DELETE";

        @Override
        public String getMethod() {
            return METHOD_NAME;
        }

        public HttpDeleteWithBody(final String uri) {
            super();
            setURI(URI.create(uri));
        }

        public HttpDeleteWithBody(final URI uri) {
            super();
            setURI(uri);
        }

        public HttpDeleteWithBody() {
            super();
        }
    }


}
